package fpzhan.plane.program.manager;

import com.alibaba.fastjson.JSONObject;
import fpzhan.plane.program.connect.RunFlow;
import fpzhan.plane.program.connect.CodeBlockContext;
import fpzhan.plane.program.proxy.CheckParamProxy;
import fpzhan.plane.program.proxy.CodeBlockProxy;
import fpzhan.plane.program.proxy.ProxyName;
import fpzhan.plane.program.proxy.SpeedProxy;
import fpzhan.plane.program.struct.CodeBlockStruct;
import fpzhan.plane.program.struct.CommentStruct;
import fpzhan.plane.program.struct.StructName;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class PlaneProgramManager {

    private static boolean useProxy=false;

    private static boolean useStruct=false;

    private static ProxyManager proxyManager = new ProxyManager();

    private static StructManager structManager = new StructManager();

    private static Map<String, RunFlow> flowMap = new HashMap<>();

    static {
        PlaneProgramManager.registerProxy(new CheckParamProxy(ProxyName.CHECK_PARAM_PROXY));
        PlaneProgramManager.registerProxy(new SpeedProxy(ProxyName.SPEED_PROXY));
        PlaneProgramManager.registerStruct(new CommentStruct(StructName.COMMENT_STRUCT));
    }

    private PlaneProgramManager() {
    }

    public static RunFlow createFlow(String name) {
        if(!useProxy){
            useProxy(ProxyName.CHECK_PARAM_PROXY);
        }
        if(!useStruct){
            useStruct(StructName.COMMENT_STRUCT);
        }
        RunFlow flow = new RunFlow(name, new CodeBlockContext(
                new HashMap<>(),
                new HashMap<>(),
                new HashMap<>(),
                proxyManager.getProxys(),
                structManager.getStruct())

        );
        flowMap.put(name, flow);
        return flow;
    }

    public static void registerProxy(CodeBlockProxy proxy) {
        proxyManager.register(proxy);
    }

    public static void registerStruct(CodeBlockStruct struct) {
        structManager.register(struct);
    }

    public static void useProxy(String... proxyName) {
        useProxy=true;
        proxyManager.useKey(proxyName);
    }

    public static void useStruct(String structName) {
        useStruct=true;
        structManager.use(structName);
    }


    public static JSONObject run(String... names) throws Exception {
        JSONObject json = new JSONObject(new LinkedHashMap<>());
        for (String name : names) {
            if (flowMap.get(name) != null) {
                flowMap.get(name).compose();
                json.put("FLOW:" + name, flowMap.get(name).run());
            }
        }
        return json;
    }

}
